package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmMaterialDto;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.search.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional

public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClient fastDFSClient;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String uploadFile=null;
        try {
            uploadFile = fastDFSClient.uploadFile(multipartFile);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial wmMaterial =new WmMaterial();

        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(uploadFile);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);
        wmMaterial.setUrl(fileServerUrl+uploadFile);


        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        if (dto.getIsCollected()!=null){

            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollected());
        }
        Page<WmMaterial>page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> wmMaterialIPage = this.page(page, queryWrapper);
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),wmMaterialIPage.getTotal());
        List<WmMaterial> wmMaterials = wmMaterialIPage.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
                    wmMaterial.setUrl(fileServerUrl+wmMaterial.getUrl());
        }
        result.setData(wmMaterials);
        return result;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if (id==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前素材被引用不能删除");
        }

        WmUser user = WmThreadLocalUtils.getUser();
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        queryWrapper.eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        WmMaterial material = this.getOne(queryWrapper);
        if (material==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String url = material.getUrl();
        fastDFSClient.delFile(url);
        this.removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if(id == null || (!WemediaContans.CANCEL_COLLECT_MATERIAL.equals(type)&&!WemediaContans.COLLECT_MATERIAL.equals(type))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 根据ID 和 登录用户ID 进行收藏修改
        update(
                Wrappers.<WmMaterial>lambdaUpdate()
                        .set(WmMaterial::getIsCollection,type)
                        .eq(WmMaterial::getId,id)
                        .eq(WmMaterial::getUserId,user.getId())
        );

        return ResponseResult.okResult();
    }
}
